from waveapi import document
from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import robot_abstract
from waveapi import ops

from voteDb import voteDB

def AddParticipants(context, waveid, participants):
  for participant in participants:
    context.AddOperation(ops.Operation(ops.WAVELET_ADD_PARTICIPANT, "googlewave.com!" + waveid, "googlewave.com!conv+root", blip_id='', index=-1, prop=participant))

def CreateWave(context, title, participants, gadget_url, deltas):
  nw = robot_abstract.NewWave(context, participants)
  nw.SetTitle(title)
  nwblip = context.GetBlipById(nw.GetRootBlipId())
  newgadget = document.Gadget(gadget_url, deltas)
  nwblip.GetDocument().AppendElement(newgadget)
  return nw

def OnDocChangedHandler(properties, context):
  items_to_work = voteDB.WorkGet("work_in", 10)
  for item in items_to_work:

    if item['gets']['queue_id'] == "add_participant":
      waveid = item['gets']['waveid']
      participants = item['gets']['participants'].split(",")
      AddParticipants(context, waveid, participants)

    elif item['gets']['queue_id'] == "create_debate":
      contentid = item['gets']['contentid']
      new_wave_title = item['gets']['newwavetitle']
      gadget_url = item['gets']['gadgeturl']
      participants = item['gets']['participants'].split(",")
      newdeltas = {
        'contentid': contentid
      }
      new_wave = CreateWave(context, new_wave_title, participants, gadget_url, newdeltas)

    elif item['gets']['queue_id'] == "create_point":
      gadget_url = item['gets']['gadgeturl']
      new_wave_title = item['gets']['newwavetitle']
      nextcontentid = item['gets']['contentid']
      newcontent = item['gets']['content']
      participants = item['gets']['participants'].split(",")
      newdeltas = {
        'nextcontentid': nextcontentid,
        'newcontent': newcontent
      }
      new_wave = CreateWave(context, new_wave_title, participants, gadget_url, newdeltas)

if __name__ == '__main__':
  myBot = robot.Robot('dan-debatewise',
    image_url   = 'http://dan-debatewise.appspot.com/static/redhat_small_normal.png',
    version     = '42',
    profile_url = 'http://dan-debatewise.appspot.com/')
  myBot.RegisterHandler(events.DOCUMENT_CHANGED, OnDocChangedHandler)
  myBot.Run()
